from django import forms
from web import models
from web.forms.bootstrap import BootstrapForm


class ProjectModelForm(BootstrapForm, forms.ModelForm):
    # desc = forms.CharField(widget=forms.Textarea())

    def __init__(self, request, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.request = request

    class Meta:
        model = models.Project
        fields = ['name', 'color', 'desc']
        widgets = {
            'desc': forms.Textarea(attrs={'rows': 5})
        }

    def clean_name(self):
        """ 项目校验 """
        name = self.cleaned_data['name']
        # 1.当前用户是否已创建过此项目
        exists = models.Project.objects.filter(name=name, creator=self.request.tracer.user).exists()
        if exists:
            self.add_error('name', '项目名已存在')

        # 2.当前用户是否还有额度进行创建项目
        #    最大创建项目数量
        max_pro_num = self.request.tracer.price_policy.project_num
        #    现在已经创建的项目数量
        count = models.Project.objects.filter(creator=self.request.tracer.user).count()
        if count >= max_pro_num:
            self.add_error('name', '您当前可创建的项目数量已达最大，无法继续创建新的项目')

        return name
